/*
 * RGB565.c
 *
 * Created: 2012-06-24 18:57:17
 *  Author: Sebastian_2
 */ 

#include <string.h> // memcpy
#include "RGB565.h"
#include "SSD1289.h"

FRESULT ShowRGB565(char *fileName, point *p) {
	FRESULT r;
	FIL file;
	UINT bytesRead;
	RGB565Header h;
		
	uint16_t bufSize = 512;
	uint16_t buffer[bufSize];
		
	r = f_open(&file, fileName, FA_READ);
	if(r) return r;
		
	r = f_read(&file, buffer, 10, &bytesRead);
	if(r) return r;
		
	memcpy(&h, buffer, sizeof(h));
	
	if(h.magic != 0x5235) return FR_INVALID_OBJECT;
		
	uint16_t width = h.width;
	uint16_t height = h.height;
	uint32_t pixels = h.pixels;
		
	uint16_t tmp = pixels/bufSize;
	uint16_t rest = pixels%bufSize;
		
	uint16_t x = p->x + width;
	uint16_t y = p->y + height;
	point p2 = {x, y};
	SSD1289_SetPaintArea(p, &p2);
	
	SSD1289_Select();
	
	for(uint8_t i = 0; i < (uint8_t)tmp; i++)
	{
		r = f_read(&file, buffer, sizeof(buffer), &bytesRead);
		for(uint16_t k = 0; k < bufSize; k++)
		{
			SSD1289_WriteDataFast(buffer[k]);
		}
	}
	
	if(rest > 0)
	{
		r = f_read(&file, buffer, rest*16, &bytesRead);
		for(uint16_t k = 0; k < rest; k++)
		{
			SSD1289_WriteDataFast(buffer[k]);
		}
	}
	
	SSD1289_Deselect();
	
	f_close(&file);
	
	return r;
}